import { Injectable } from '@nestjs/common';
import { SignonDto } from '../dto/auth/login-user.dto';
import * as svgCaptcha from 'svg-captcha';
import { UserService } from './user.service';
import { JwtService } from '@nestjs/jwt';
import { User } from '../entities/user.entity';

type CaptchaObj = {
  text: string;
  data: string;
};

export type MenuItem = {
  label: string;
  key?: string;
  icon?: string;
  type?: string;
  children?: MenuItem[];
};

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwt: JwtService,
  ) {}

  // 生成验证码
  createCaptcha(): CaptchaObj {
    const captcha = svgCaptcha.create({
      size: 4,
      fontSize: 50,
      width: 80,
      height: 32,
      background: '#cc9966',
    });
    return captcha;
  }

  // 登录
  async login(signonDto: SignonDto): Promise<{
    token: string;
    userInfo: Partial<User>;
    menu: MenuItem[];
  }> {
    let { userInfo, menu } = await this.userService.findUserLogin(signonDto);
    let token = await this.jwt.signAsync(
      {
        phone: signonDto.phone,
        WaiFCode: 'WaiFCode' + signonDto.phone,
      },
      {
        expiresIn: '10d', // 局部设置过期时间
      },
    );
    return {
      token,
      userInfo,
      menu,
    };
  }

  // 获取用户
  async adminGetUsers(
    pageNum: number = 1,
    pageSize: number = 10,
    keyword?: string,
  ): Promise<{
    total: number;
    users: User[];
  }> {
    return await this.userService.adminGetUsers(pageNum, pageSize, keyword);
  }

  // 更新用户权限
  async adminUpdateUser({ _id, isAdmin }: { _id: string; isAdmin: string }) {
    return await this.userService.adminUpdateUser({ _id, isAdmin });
  }
}
